<?php 

/**
 * Vega Framework
 *
 * @url http://vega.com.vn
 * @url http://clip.vn
 */

class Vega_Log_WebDebug
{
	protected static $_instance = null;
	
	protected 
		$_time			= null,
		$_config		= null,
		$_queries	 	= array(),
		$_querytimes	= array();
	
	public function __construct()
	{
	}
	
	public static function getDebugger()
    {
        if (null === self::$_instance)
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
		
	public function show()
	{
		$script = '
			<script>
				function webDebugToggle(id)
				{
					if (document.getElementById(id).style.display == "none")
					{
						document.getElementById(id).style.display = "block";
					}
					else document.getElementById(id).style.display = "none"
				}
				
			</script>
		';
		
		$css = '
			<style type="text/css">
				#webDebug {
					font-family: Arial;
					font-size: 12px;
					font-weight: bold;
					line-height: 12px;
					color: #FFFFFF;
					text-align: left;
					margin: 0;
					padding: 0;
				}
				
				#webDebugBar {
					position: fixed;
					opacity: 0.9;
					padding: 5px;
					bottom: 0;
					right: 0;
					width: 400px;
					background: #818181;
					z-index: 10000;
				}
				
				*html #webDebugBar {
					position: absolute;
				}
				
				#webDebugDetails {
					display: inline;
					margin: 3px 0pt;
				}
				
				#webDebugBar a {
					color: white;
					text-decoration: none;
				}
				
				#webDebugDetails li {
					border-right: 1px solid white;
					display: inline;
					padding: 0pt 5px;
				}
				
				.webDebugPanel {
					position: fixed;
					bottom: 0;
					left: 0;
					right: 0;
					color: #000000;
					font-weight: normal;
					padding: 0 10px 10px 10px;
					width: 99%;
					min-height: 50px;
					max-height: 300px;
					overflow: auto;
					background: #EFEFEF;
					border-top: 1px solid #A4A4A4;
					z-index:9999;
				}
				
				*html #webDebugConfiguration {
					position: absolute;
				}
				
				#webDebugConfiguration a {
					color: #000000;
					text-decoration: none;
				}
				
				span.header {
					font-size: 16px;
					font-weight: bold;
				}
			</style> 
		';
		
		echo $script.$css;
		
		// memory used
	    $memoryInfo = '';
	    if (function_exists('memory_get_usage'))
	    {
	      $totalMemory = sprintf('%.1f', (memory_get_usage() / 1024));
	      $memoryInfo = '<li>'.'Memory: '.$totalMemory.' KB</li>';
	    }
	    
	    // execution time
	    $totalTime = $this->_time * 1000;
      	$totalTime = sprintf(($totalTime <= 1) ? '%.2f' : '%.0f', $totalTime);
      	$timeInfo = '<li>'.$totalTime.' ms</li>';
      	
	    $result = '
	    	<div id="webDebug">
	    		<div id="webDebugBar">
	    			<ul id="webDebugDetails">
						<li><a href="javascript:void(0);" onclick="webDebugToggle(\'webDebugQueryLog\')">Query Log</a></li>
	    				<li><a href="javascript:void(0);" onclick="webDebugToggle(\'webDebugConfiguration\')">Configuration</a></li>
	    				'.$memoryInfo.'
	    				'.$timeInfo.'
	    			</ul>
	    			<a style="margin-left:5px" href="#" onclick="document.getElementById(\'webDebug\').style.display=\'none\'; return false;"><b>X</b></a>
	    		</div>
	    		
	    		<div id="webDebugConfiguration" class="webDebugPanel" style="display: none"><span class="header">Informations</span>
	    			'.$this->_formatArrayAsYaml('>>>>>>>>>> Configs <<<<<<<<<<<<', $this->_config).'
	    			'.$this->_formatArrayAsYaml('>>>>>>>>>> Globals <<<<<<<<<<<<', $this->_getGlobalsArray()).'
	    		</div>
				
				<div id="webDebugQueryLog" class="webDebugPanel" style="display: none"><span class="header">Query Log | </span>
	    			'.$this->_getQueryInfo().'
	    		</div>
	    	</div>
	    ';
	    
	    echo $result;
	}

	public function setTime($time)
	{
		$this->_time = $time;	
	}
	
	public function setConfig($config)
	{
		$this->_config = $config;
	}

	protected function _formatArrayAsYaml($name, $values)
	{
		require_once 'Vega/Log/Spyc.php';
		
		$result = '
    		<h3><a href="#" onclick="webDebugToggle(\'webDebug'.$name.'\'); return false;"><b>'.$name.'</b></a></h3>
    		<div id="webDebug'.$name.'" style="display: none"><pre>'.htmlentities(Spyc::YAMLDump($values), ENT_QUOTES).'</pre></div>
    	';

    	return $result;
	}
	
	protected function _getGlobalsArray()
  	{
    	$values = array();
    	foreach (array('cookie', 'server', 'get', 'post', 'files', 'env', 'session') as $name)
    	{
      		if (!isset($GLOBALS['_'.strtoupper($name)]))
      		{
        		continue;
      		}

      		$values[$name] = array();
      		foreach ($GLOBALS['_'.strtoupper($name)] as $key => $value)
      		{
        		$values[$name][$key] = $value;
     		}
      		
     		ksort($values[$name]);
    	}

    	ksort($values);

    	return $values;
  	}
	
	protected function _getQueryInfo()
	{
		if($this->_queries)
		{
			$result = 'Queries: ' . count($this->_queries) . ' - Total: <font color="blue">' . array_sum($this->_querytimes) . '</font> s - Slowest: <font color="red">' . max($this->_querytimes) . '</font> s<br/>';
		
			foreach($this->_queries AS $i => $query)
			{
				$result .= '<br/><b>#' . ($i+1) . '</b> - <font color="blue">' . $this->_querytimes[$i] . '</font> s<br/>' . $query . '<br/>';
			}
		}
		else return null;
		
		return $result;
	}
	
	public function addQueryInfo($sql, $time)
	{
		array_push($this->_queries, $sql);
		array_push($this->_querytimes, $time);
	}
}